/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.documentar.view;

import br.com.documentar.interfacee.InterfaceAutenticarUsuario;
import br.com.documentar.model.LoginModel;
import br.com.documentar.util.ConvertPasswordToMD5;
import br.com.documentar.util.UtilitariosCampos;
import br.com.documentar.util.setFiltroCampo;
import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;

/**
 *
 * @author Santos
 */
public class LoginView extends javax.swing.JFrame implements InterfaceAutenticarUsuario {

    private final br.com.documentar.controller.LoginController control = new br.com.documentar.controller.LoginController();
    private final br.com.documentar.model.LoginModel model = control.returnModelLogin();

    /**
     * Creates new form LoginView
     */
    public LoginView() {
        initComponents();
        iniciarListener();
        setFiltroCampo();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        textFieldUsuario = new javax.swing.JTextField();
        jCheckBox1 = new javax.swing.JCheckBox();
        buttonEntrar = new javax.swing.JButton();
        passwordFieldSenha = new javax.swing.JPasswordField();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        logoMarca = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Login do Usuário");
        setResizable(false);

        jLabel1.setText("Usuário");

        jLabel2.setText("Senha");

        jCheckBox1.setText("Esqueci a senha");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        buttonEntrar.setMnemonic('E');
        buttonEntrar.setText("Entrar");
        buttonEntrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonEntrarActionPerformed(evt);
            }
        });

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setText("Entre com seu usuário e senha");

        logoMarca.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        logoMarca.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/documentar/iconesLogin/logoMarcaLogin.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jCheckBox1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(buttonEntrar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(passwordFieldSenha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
                        .addComponent(textFieldUsuario, javax.swing.GroupLayout.Alignment.LEADING)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(logoMarca)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(jLabel3)
                        .addGap(43, 43, 43)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textFieldUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(passwordFieldSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(7, 7, 7)
                        .addComponent(jCheckBox1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(buttonEntrar)
                        .addGap(0, 31, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(logoMarca, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jSeparator1))))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonEntrarActionPerformed
        LoginSystem();

    }//GEN-LAST:event_buttonEntrarActionPerformed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        JOptionPane.showMessageDialog(this, " Opção em implementação!");
    }//GEN-LAST:event_jCheckBox1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LoginView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonEntrar;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel logoMarca;
    private javax.swing.JPasswordField passwordFieldSenha;
    private javax.swing.JTextField textFieldUsuario;
    // End of variables declaration//GEN-END:variables

    @Override
    public void CarregarVariaveis() {
        model.setUsuario(textFieldUsuario.getText());
        model.setSenha(ConvertPasswordToMD5.convertPasswordToMD5(passwordFieldSenha));
    }

    @Override
    public boolean AutenticarUsuario(LoginModel model) {
        return control.AutenticarUsuario(model);
    }

    public void LoginSystem() {
        CarregarVariaveis();
        if (model.getUsuario().equals("") || model.getSenha().equals("")) {
            if (model.getUsuario().equals("")) {
                JOptionPane.showMessageDialog(this, "Favor informar o Usuário!!!");
                textFieldUsuario.requestFocus();
            } else if (model.getSenha().equals("")) {
                JOptionPane.showMessageDialog(this, "Favor informar a Senha!!!");
                passwordFieldSenha.requestFocus();
            }

        } else {
            if (AutenticarUsuario(model)) {
                //torna publico para todo o sistema o usuário que está conectado no momento
                UtilitariosCampos.setUsuario(Integer.parseInt(model.getUsuario()));
                br.com.documentar.view.PrincipalView.main();
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "Usuário ou senha inválidos");
                passwordFieldSenha.requestFocus();
            }
        }
    }

    KeyAdapter Teclado = new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            Component c = e.getComponent();
            switch (e.getKeyCode()) {
                case KeyEvent.VK_ENTER: {//Botão Enter
                    if (textFieldUsuario.isFocusable() && passwordFieldSenha.getText().equals("")) {
                        passwordFieldSenha.requestFocus();
                    } else if (passwordFieldSenha.isFocusable()) {
                        LoginSystem();
                    }
                    break;
                }
                case KeyEvent.VK_UP: {//Botão UP
                    c.transferFocusBackward();
                    break;
                }
                case KeyEvent.VK_DOWN: {//Botão DOWN
                    c.transferFocus();
                    break;
                }
            }
        }
    };

    private void iniciarListener() {
        textFieldUsuario.addKeyListener(Teclado);
        passwordFieldSenha.addKeyListener(Teclado);
    }

    private void setFiltroCampo() {
        textFieldUsuario.setDocument(new setFiltroCampo(10, "NumeroInteiro"));
        passwordFieldSenha.setDocument(new setFiltroCampo(32, "Texto", 'P'));
    }
}
